import React, { useEffect, useState, useCallback } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { Menu } from "antd";
import { iconMap } from "../MainLayout/iconMap";

// 工具函数：规范化路径（去除末尾斜杠）
const normalizePath = (path) => {
  return path.replace(/\/$/, "");
};

// 加载路由并生成菜单配置
const loadRoutes = async () => {
  try {
    const { routesConfig } = await import("../../routes/config");
    const layoutRoute = routesConfig.find(
      (route) => route.element && route.children?.length
    );
    const menuRoutes = layoutRoute ? layoutRoute.children : routesConfig;
    // return []
    return generateMenu(menuRoutes);
  } catch (error) {
    console.error("加载路由配置失败:", error);
    return [];
  }
};

// 递归生成菜单结构
const generateMenu = (routes, parentPath = "") => {
  const normalizedParent = parentPath ? normalizePath(parentPath) : "";

  return routes
    .filter((route) => !route.meta?.hideInMenu && !route.index)
    .map((route) => {
      let fullPath = normalizedParent
        ? `${normalizedParent}/${route.path.replace(/^\//, "")}`
        : route.path;
      if (parentPath === "/") fullPath = "/" + route.path;
      const IconComponent = iconMap[route.meta?.icon];
      const icon = IconComponent ? <IconComponent /> : null;

      const children = route.children
        ? generateMenu(route.children, fullPath)
        : [];

      return {
        key: fullPath,
        icon: icon,
        label: route.meta?.title || "未命名",
        path: fullPath,
        children: children.length > 0 ? children : undefined,
      };
    });
};

// 工具函数：获取所有需要展开的父菜单 key
const getOpenKeys = (items, currentKey) => {
  // 递归查找目标key的所有父级key
  const findParentKeys = (items, targetKey, parentKeys = []) => {
    for (const item of items) {
      // 记录当前路径（包含当前item的key）
      const currentParentKeys = [...parentKeys, item.key];

      // 找到目标key，返回所有父级（排除自身）
      if (item.key === targetKey) {     
        return currentParentKeys.slice(0, -1);
      }

      // 若有子节点，递归查找
      if (item.children?.length) {
        const result = findParentKeys(
          item.children,
          targetKey,
          currentParentKeys
        );
        // 只有找到结果时才返回，避免空数组干扰
        if (result !== null) {
          return result;
        }
      }
    }
    // 未找到目标，返回null（明确标识未找到）
    return null;
  };
  // 执行查找，若未找到则返回空数组
  const openKeys = findParentKeys(items, currentKey) || [];
  // console.log('openKeys',openKeys)

  return openKeys;
};

// 菜单组件
const MenuItems = (props) => {
  const navigate = useNavigate();
  const location = useLocation();
  const [navItems, setNavItems] = useState([]);
  const [openKeys, setOpenKeys] = useState([]);
  const { collapsed } = props;

  // 用useCallback缓存函数，确保引用稳定
  const findMenuItem = useCallback((items, targetPath) => {
    for (const item of items) {
      if (item.key === targetPath) {
        return item;
      }
      if (item.children?.length) {
        const childItem = findMenuItem(item.children, targetPath);
        if (childItem) return childItem;
      }
      if (!item.children?.length && targetPath.startsWith(`${item.key}/`)) {
        return item;
      }
    }
    return null;
  }, []); // 空依赖数组，函数只会创建一次

  // 加载菜单数据
  useEffect(() => {
    const fetchNavItems = async () => {
      try {
        const menuData = await loadRoutes();
        setNavItems(menuData);
      } catch (error) {
        console.error("菜单加载失败", error);
      }
    };
    fetchNavItems();
  }, []);

  // 路由变化时更新选中和展开状态 - 已添加findMenuItem到依赖
  useEffect(() => {
    if (navItems.length) {
      const matchItem = findMenuItem(navItems, location.pathname);
      if (matchItem) {
        const newOpenKeys = getOpenKeys(navItems, matchItem.key);
        setOpenKeys(newOpenKeys);
      }
    }
  }, [navItems, location.pathname, findMenuItem]); // 这里添加了findMenuItem
  //菜单点击事件跳转路由
  const handleMenuItem = (e) => {
    const menuItem = findMenuItem(navItems, e.key);
    if (menuItem?.path) {
      navigate(menuItem.path);
    }
  };
  //菜单打开改变事件
  const handleOpenChange = (newOpenKeys) => {
    console.log(newOpenKeys, "newOpenKeys");
    setOpenKeys(newOpenKeys);
  };
  //获取当前路由key
  const getSelectedKey = () => {
    const matchItem = findMenuItem(navItems, location.pathname);
    return matchItem ? [matchItem.key] : [];
  };

  return (
    <Menu
      theme="dark"
      mode="inline"
      selectedKeys={getSelectedKey()}
      openKeys={openKeys}
      onOpenChange={handleOpenChange}
      items={navItems}
      onClick={handleMenuItem}
      inlineCollapsed={collapsed}
    />
  );
};

export default MenuItems;
